package com.example.appmanager.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.appmanager.Appconfig.Appconfig;
import com.example.appmanager.MainActivity;
import com.example.appmanager.R;
import com.example.appmanager.adapter.HomeFragmentAdapter;
import com.example.appmanager.entity.AppEntity;
import com.example.appmanager.services.AllresposeService;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import static com.yanzhenjie.nohttp.NoHttp.getContext;

/*
这个是主頁的Fragment
* */
public class HomeFragment extends AppCompatActivity {
    private RecyclerView recycler_loading;//正在 下载
    private RecyclerView recycler_downed;//已经下载
    private AppEntity.RowsBean appEntity = new AppEntity.RowsBean();
    private List<AppEntity.RowsBean> appEntities = new ArrayList<>();
    private HomeFragmentAdapter appAdapter;
    private static FileOutputStream fileOuputStream;
    private ImageView imageView;//这个是返回的按钮
    private int appId = 9;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);

    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_home);
        initUi();//要先进行数据的初始化

        if (!(appEntity==null)){
            getData(appId);
        }
        getOnClickListener();

        Log.d("HomeFragment", "进入HomeFragment界面！！");
    }

    private void getOnClickListener() {
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
            }
        });
    }

    /*从网络获取数据然后进行下载*/
    private void getData(int i) {
//        这个是正在下载
        if (appEntity != null) {
            appEntities.add(appEntity);
            appAdapter.setData(this, appEntities, i);
            appAdapter.notifyDataSetChanged();
            recycler_loading.setAdapter(appAdapter);
            Log.d("GalleryFragment", appEntities.toString());
            downloadFile(Appconfig.BASE_APP + "滴滴快车.apk");
        }
        else {
            return;
        }
    }
/*请求下载*/
    private void downloadFile(final String fileUrl) {//传一个APP的绝对地址
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Appconfig.BASE_APP)
                .client(Appconfig.CLIENT) //这是设置请求的时间等信息 连接时间  上传等时间
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //AllresposeService request = retrofit.create(AllresposeService.class);
        final AllresposeService downloadService = retrofit.create(AllresposeService.class);

        Call<ResponseBody> call = downloadService.download(fileUrl);

        call.enqueue(new Callback<ResponseBody>() {
            @SuppressLint("StaticFieldLeak")
            @Override
            public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    Log.e("Download", "server contacted and has file");
                    new AsyncTask<Void, Long, Void>() {
                        @Override
                        protected Void doInBackground(Void... voids) {
                            boolean writtenToDisk = writeResponseBodyToDisk(response.body(), appEntity.getAppname() + ".apk");

                            Log.e("Download", "file download was a success? " + writtenToDisk);
                            return null;
                        }

                    }.execute();

                } else {
                    Log.e("Download", "server contact failed");
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("Download", "error :" + t.getMessage());
            }
        });
    }

    /*下载流的转化*/
    private boolean writeResponseBodyToDisk(ResponseBody body, String savaName) {
        try {
            // todo change the file location/name according to your needs
            File futureStudioIconFile = new File(savaName);

            Log.d("Download", getExternalFilesDir(null) + File.separator + savaName);
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;
                inputStream = body.byteStream();
                outputStream = new FileOutputStream(futureStudioIconFile);
                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;

                    Log.w("saveFile", "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }


    /*初始化界面的控件*/
    private void initUi() {
        recycler_loading = findViewById(R.id.recyclerView_loading);//正在下载
        // recycler_downed = findViewById(R.id.spinner);//已经下载
        imageView = findViewById(R.id.imageView);
        appAdapter = new HomeFragmentAdapter(getApplicationContext(), null);
        //.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycler_loading.setLayoutManager(new LinearLayoutManager(getParent()));
        ///bundle.putString("AppAdapter",String.valueOf(app));

       if (!(getIntent().getExtras()==null)){
           String app = (String) getIntent().getExtras().get("AppAdapter");
        appEntity = JSONObject.parseObject(app, AppEntity.RowsBean.class);
        appId = appEntity.getId();
        Log.d("HomeFragment", appEntity.toString());
       }
    }


}
